package com.chx.three.mama.activities;

import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.chx.three.mama.R;
import com.chx.three.mama.utils.Constants;
import com.chx.three.mama.utils.DensityUtil;
import com.chx.three.mama.utils.SPHelper;
import com.chx.three.mama.utils.TimeHelper;
import com.chx.three.mama.view.PicLayout;
import com.chx.three.mama.view.SildingFinishLayout;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ContentView(R.layout.activity_create_bbs)
public class CreateBbsActivity extends FragmentActivity
        implements SildingFinishLayout.OnSildingFinishListener,
        View.OnClickListener,
        PicLayout.OnObtainPictureListener {
    public static final int OBTAIN_PICK_IMAGE = 101;
    public static final int OBTAIN_CAMERA_IMAGE = 102;
    @ViewInject(R.id.bbs_create_back)
    ImageButton mBack;
    @ViewInject(R.id.bbs_create_silding_finish)
    SildingFinishLayout sildingFinish;
    @ViewInject(R.id.bbs_create_pub)
    TextView mPub;
    @ViewInject(R.id.bbs_create_ring)
    TextView mring;
    @ViewInject(R.id.bbs_create_title)
    EditText mTitle;
    @ViewInject(R.id.bbs_create_content)
    EditText mContent;
    @ViewInject(R.id.bbs_create_obtain_pic)
    PicLayout obtainPicLayout;
    @ViewInject(R.id.bbs_create_icon)
    ImageView mIcon;
    List<Fragment> fragmentList;
    @ViewInject(R.id.bbs_create_select)
    LinearLayout mCheckRing;
    //暂时写死了圈子名称
    HashMap<String,String> rings=new HashMap<>();
    private String qid;
    private PopupWindow mPopup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        sildingFinish.setOnSildingFinishListener(this);
        mBack.setOnClickListener(this);
        initData();
        setPublish();
    }
    private void setTitlePopupWindow(){
        View view= LayoutInflater.from(this).inflate(R.layout.layout_bbs_create_select_bbs,null);
        setOnCheckRing(view);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindow().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        mPopup = new PopupWindow(view,metrics.widthPixels, DensityUtil.dip2px(this, 220),true);
        mPopup.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
        mPopup.showAtLocation(sildingFinish, Gravity.BOTTOM, 0, 0);
        

    }

    public void setOnCheckRing(View view){
        TextView ring1=(TextView)view.findViewById(R.id.bbs_title_1);
        TextView ring2=(TextView)view.findViewById(R.id.bbs_title_2);
        TextView ring3=(TextView)view.findViewById(R.id.bbs_title_3);
        TextView ring4=(TextView)view.findViewById(R.id.bbs_title_4);
        TextView ring5=(TextView)view.findViewById(R.id.bbs_title_5);
        TextView ring6=(TextView)view.findViewById(R.id.bbs_title_6);
        TextView ring7=(TextView)view.findViewById(R.id.bbs_title_7);
        TextView ring8=(TextView)view.findViewById(R.id.bbs_title_8);
        TextView ring9=(TextView)view.findViewById(R.id.bbs_title_9);
        TextView ring10=(TextView)view.findViewById(R.id.bbs_title_10);
        TextView ring11=(TextView)view.findViewById(R.id.bbs_title_11);
        TextView ring12=(TextView)view.findViewById(R.id.bbs_title_12);
        //设置点击事件
        ring1.setOnClickListener(this);
        ring2.setOnClickListener(this);
        ring3.setOnClickListener(this);
        ring4.setOnClickListener(this);
        ring5.setOnClickListener(this);
        ring6.setOnClickListener(this);
        ring7.setOnClickListener(this);
        ring8.setOnClickListener(this);
        ring9.setOnClickListener(this);
        ring10.setOnClickListener(this);
        ring11.setOnClickListener(this);
        ring12.setOnClickListener(this);
        //设置背景颜色
        ring1.setBackgroundResource(R.drawable.a_shape_white_bg);
        ring2.setBackgroundResource(R.drawable.a_shape_white_bg);
        ring3.setBackgroundResource(R.drawable.a_shape_white_bg);
        ring4.setBackgroundResource(R.drawable.a_shape_white_bg);
        ring5.setBackgroundResource(R.drawable.a_shape_white_bg);
        ring6.setBackgroundResource(R.drawable.a_shape_white_bg);
        ring7.setBackgroundResource(R.drawable.a_shape_white_bg);
        ring8.setBackgroundResource(R.drawable.a_shape_white_bg);
        ring9.setBackgroundResource(R.drawable.a_shape_white_bg);
        ring10.setBackgroundResource(R.drawable.a_shape_white_bg);
        ring11.setBackgroundResource(R.drawable.a_shape_white_bg);
        ring12.setBackgroundResource(R.drawable.a_shape_white_bg);
        //设置字体颜色
        ring1.setTextColor(Color.BLACK);
        ring2.setTextColor(Color.BLACK);
        ring3.setTextColor(Color.BLACK);
        ring4.setTextColor(Color.BLACK);
        ring5.setTextColor(Color.BLACK);
        ring6.setTextColor(Color.BLACK);
        ring7.setTextColor(Color.BLACK);
        ring8.setTextColor(Color.BLACK);
        ring9.setTextColor(Color.BLACK);
        ring10.setTextColor(Color.BLACK);
        ring11.setTextColor(Color.BLACK);
        ring12.setTextColor(Color.BLACK);
        //设置选择框的样式
        String s = mring.getText().toString();
        if(s.equals(ring1.getText())){
            ring1.setTextColor(getResources().getColor(R.color.tab_text_color));
            ring1.setBackgroundResource(R.drawable.a_shape_white_pink_stroken);
        }
        if(s.equals(ring2.getText())){
            ring2.setTextColor(getResources().getColor(R.color.tab_text_color));
            ring2.setBackgroundResource(R.drawable.a_shape_white_pink_stroken);
        }
        if(s.equals(ring3.getText())){
            ring3.setTextColor(getResources().getColor(R.color.tab_text_color));
            ring3.setBackgroundResource(R.drawable.a_shape_white_pink_stroken);
        }
        if(s.equals(ring4.getText())){
            ring4.setTextColor(getResources().getColor(R.color.tab_text_color));
            ring4.setBackgroundResource(R.drawable.a_shape_white_pink_stroken);
        }
        if(s.equals(ring5.getText())){
            ring5.setTextColor(getResources().getColor(R.color.tab_text_color));
            ring5.setBackgroundResource(R.drawable.a_shape_white_pink_stroken);
        }
        if(s.equals(ring6.getText())){
            ring6.setTextColor(getResources().getColor(R.color.tab_text_color));
            ring6.setBackgroundResource(R.drawable.a_shape_white_pink_stroken);
        }
        if(s.equals(ring7.getText())){
            ring7.setTextColor(getResources().getColor(R.color.tab_text_color));
            ring7.setBackgroundResource(R.drawable.a_shape_white_pink_stroken);
        }
        if(s.equals(ring8.getText())){
            ring8.setTextColor(getResources().getColor(R.color.tab_text_color));
            ring8.setBackgroundResource(R.drawable.a_shape_white_pink_stroken);
        }
        if(s.equals(ring9.getText())){
            ring9.setTextColor(getResources().getColor(R.color.tab_text_color));
            ring9.setBackgroundResource(R.drawable.a_shape_white_pink_stroken);
        }
        if(s.equals(ring10.getText())){
            ring10.setTextColor(getResources().getColor(R.color.tab_text_color));
            ring10.setBackgroundResource(R.drawable.a_shape_white_pink_stroken);
        }
        if(s.equals(ring10.getText())){
            ring10.setTextColor(getResources().getColor(R.color.tab_text_color));
            ring10.setBackgroundResource(R.drawable.a_shape_white_pink_stroken);
        }
        if(s.equals(ring11.getText())){
            ring11.setTextColor(getResources().getColor(R.color.tab_text_color));
            ring11.setBackgroundResource(R.drawable.a_shape_white_pink_stroken);
        }
        if(s.equals(ring12.getText())){
            ring12.setTextColor(getResources().getColor(R.color.tab_text_color));
            ring12.setBackgroundResource(R.drawable.a_shape_white_pink_stroken);
        }

    }

    /**
     * 发布主题
     */
    private void setPublish() {
        mCheckRing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setTitlePopupWindow();
            }
        });
        mPub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RequestQueue requestQueue= Volley.newRequestQueue(CreateBbsActivity.this);
                StringRequest request =
                        new StringRequest(
                                Request.Method.POST,
                                "http://www.qubaobei.com/ios/api/adr_post_one_test.php",
                                new Response.Listener<String>() {
                                    @Override
                                    public void onResponse(String s) {
                                            CreateBbsActivity.this.finish();
                                    }
                                },
                                new Response.ErrorListener() {
                                    @Override
                                    public void onErrorResponse(VolleyError volleyError) {
                                            Toast.makeText(CreateBbsActivity.this,"发布失败>.~<",Toast.LENGTH_SHORT).show();
                                    }
                                }
                        ){
                            @Override
                            protected Map<String, String> getParams() throws AuthFailureError {
                                HashMap<String,String> map=new HashMap<String, String>();
                                map.put("o_user_id", SPHelper.getUserId()+"");
                                map.put("site", "2");
                                map.put("content", mContent.getText().toString());
                                map.put("crc_qq", "MTE3Nzk1MSw0NTkwNTE0LDI1MTg2MTk7YWJjMjI2MTcxODBhNzcyMDg0NmUwM2FiNWVhMDRiOTQ=");
                                map.put("cur_version", "76.5");
                                map.put("title", mTitle.getText().toString());
                                map.put("pic_num", obtainPicLayout.getPicNum()+"");
                                map.put("qid", qid);
                                List<Bitmap> bitmapList = obtainPicLayout.getBitmapList();
                                for (int i = 0; i < bitmapList.size(); i++) {

                                    map.put("pic" + i, bitmapList.get(i).toString());

                                }
                                return map;
                            }
                        };
                requestQueue.add(request);
                requestQueue.start();
            }
        });
    }

    private void initData(){
        rings.put("10001","十月怀胎");
        rings.put("10007","育儿交流");
        rings.put("10005","女人心情");
        rings.put("10003","90后妈妈");
        rings.put("10013","80后妈妈");
        rings.put("10006","宝宝秀场");
        rings.put("10002","母乳喂养");
        rings.put("10008","夫妻情感");
        rings.put("10004","麻辣婆媳");
        rings.put("10011","美食厨房");
        rings.put("10014","时尚丽人");
        rings.put("10015","巧手DIY");
        Intent intent = getIntent();
        qid = intent.getStringExtra(Constants.BundleKey.KEY_BBS_CREATE_QID);
        String ring = rings.get(qid);
        mring.setText(ring);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0,R.anim.push_right_out);
    }

    @Override
    public void onSildingFinish() {
        finish();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.bbs_create_back:
                finish();
                break;
            case R.id.bbs_title_1:
                setRingTitle("10001");
                break;
            case R.id.bbs_title_2:
                setRingTitle("10007");
                break;
            case R.id.bbs_title_3:
                setRingTitle("10005");
                break;
            case R.id.bbs_title_4:
                setRingTitle("10003");
                break;
            case R.id.bbs_title_5:
                setRingTitle("10013");
                break;
            case R.id.bbs_title_6:
                setRingTitle("10006");
                break;
            case R.id.bbs_title_7:
                setRingTitle("10002");
                break;
            case R.id.bbs_title_8:
                setRingTitle("10008");
                break;
            case R.id.bbs_title_9:
                setRingTitle("10004");
                break;
            case R.id.bbs_title_10:
                setRingTitle("10011");
                break;
            case R.id.bbs_title_11:
                setRingTitle("10014");
                break;
            case R.id.bbs_title_12:
                setRingTitle("10015");
                break;
        }
    }

    /**
     * 点击设置圈子之后
     * @param key
     */
    public void setRingTitle(String key){
        mring.setText(rings.get(key));
        qid=key;
        if(mPopup.isShowing()){
            mPopup.dismiss();
        }
    }
    /**
     * 打开相册
     */
    @Override
    public void onObtainAlbum() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        intent.putExtra("return-data", true);
        startActivityForResult(intent, OBTAIN_PICK_IMAGE);
    }
    //相机存储图片位置
    String picFileFullName="";
    /**
     * 打开照相机
     */
    @Override
    public void onObtainCamera() {

        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File outDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            if (!outDir.exists()) {
                outDir.mkdirs();
            }
            String mTimeStr="img_"+TimeHelper.getInstance().getCurrentMillisTime();
            File outFile = new File(outDir, mTimeStr + ".jpg");
            picFileFullName = outFile.getAbsolutePath();
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile));
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            startActivityForResult(intent, OBTAIN_CAMERA_IMAGE);

        }else{
            Toast.makeText(this,"亲，你没有内存卡>.<~",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(data==null){
            return;
        }
        Bitmap bitmap=null;
        if (requestCode == OBTAIN_PICK_IMAGE) {
            if(resultCode == RESULT_OK) {
                Uri uri = data.getData();
                ContentResolver cr = this.getContentResolver();
                try {
                    bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        } else if (requestCode == OBTAIN_CAMERA_IMAGE ) {
            if(resultCode == RESULT_OK){
                 bitmap = BitmapFactory.decodeFile(picFileFullName);

            }
        }
        if(bitmap!=null){
            int sild=Math.min(bitmap.getWidth(),bitmap.getHeight());
            bitmap=Bitmap.createBitmap(bitmap,0,0,sild,sild);
            obtainPicLayout.addImage(bitmap);
        }
        obtainPicLayout.dismissDialog();
    }

    /**
     * 存储拍照的照片
     * @param photo
     */
    public static void saveImage(Bitmap photo) {
        try {
            TimeHelper helper=TimeHelper.getInstance();
            File file = Environment.getExternalStorageDirectory();
            TimeHelper time=TimeHelper.getInstance();
            File img=new File(file,"img_"+time.getCurrentMillisTime()+".png");
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(img.getPath(), false));
            photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
